from PySide6.QtWidgets import QMenu,QFileDialog,QPlainTextEdit,QMainWindow,QMessageBox
from PySide6.QtGui import QKeySequence
from PySide6.QtPrintSupport import QPrintDialog,QPrinter
from pathlib import Path

class FileMenu(QMenu):
    """文件菜单

    :param QMenu: PySide6 菜单类
    """
    def __init__(self):
        """初始化
        """
        self.__home_path = str(Path.home())
        self.__file_path = None
        super().__init__()
        self.setup_ui()
    
    def setup_ui(self):
        """设置菜单项
        """
        self.setTitle("文件(&F)")
        self.__new_file = self.addAction("新建(&N)",QKeySequence.StandardKey.New)
        self.__new_window = self.addAction("新窗口(&W)","Ctrl+Shift+N")
        self.__open_file = self.addAction("打开(&O)",QKeySequence.StandardKey.Open)
        self.__save_file = self.addAction("保存(&S)",QKeySequence.StandardKey.Save)
        self.addSeparator()
        self.__save_file_as = self.addAction("另存为(&A)",QKeySequence.StandardKey.SaveAs)
        self.__print_file = self.addAction("打印(&P",QKeySequence.StandardKey.Print)
        self.addSeparator()
        self.__exit_ = self.addAction("退出(&X)",QKeySequence.StandardKey.Close)

    def set_event_bind(self,main_window:QMainWindow,plain_text_edit:QPlainTextEdit):
        """设置事件绑定
        :param main_window: PySide6 主窗口 
        :param plain_text_edit: PySide6 纯文本编辑
        """
        # 绑定 新建 新窗口 打开 保存 另存为 打印 退出
        self.__new_file.triggered.connect(lambda: self.message_box(main_window,plain_text_edit))
        self.__open_file.triggered.connect(lambda: self.open_file(main_window,plain_text_edit))
        self.__save_file.triggered.connect(lambda: self.save_file(main_window,plain_text_edit))
        self.__save_file_as.triggered.connect(lambda: self.save_file_as(main_window,plain_text_edit))
        self.__print_file.triggered.connect(lambda: self.print_file(plain_text_edit))
        self.__exit_.triggered.connect(lambda: self.close_megbox(main_window,plain_text_edit))

    def new_file(self,main_window:QMainWindow,plain_text_edit:QPlainTextEdit):
        """新建

        :param main_window: PySide6 主窗口 
        :param plain_text_edit: PySide6 纯文本编辑
        """
        plain_text_edit.clear()
        main_window.setWindowTitle("无标题-记事本")
        self.__file_path = None

    def open_file(self,main_window: QMainWindow,plain_text_edit: QPlainTextEdit):
        """打开文件

        :param plain_text_edit: PySide6 纯文本编辑
        """
        # 获取文件路径
        self.__file_path, _ = QFileDialog.getOpenFileName(self, "打开",self.__home_path,"(*.txt);;(*.*)")

        # 文件路经不为空 读取文件
        if self.__file_path:
            with open(self.__file_path,"r") as file:
                plain_text_edit.setPlainText(file.read())
            file_name = self.get_file_name()
            main_window.file_name = file_name
                
    def save_file(self,main_window: QMainWindow,plain_text_edit: QPlainTextEdit):
        """保存文件

        :param plain_text_edit: PySide6 纯文本编辑
        """
        # 当文件路径属性存在时,直接写入文件,不存在时调用另存为
        if self.__file_path:
            file_name = self.get_file_name()
            main_window.set_window_title(False,file_name)
            with open(self.__file_path,"w") as file:
                file.write(plain_text_edit.toPlainText())
        else:
            self.__file_path = self.save_file_as(main_window,plain_text_edit)

    def save_file_as(self,main_window,plain_text_edit: QPlainTextEdit) -> str:
        """另存为

        :param plain_text_edit: PySide6 纯文本编辑
        :return: 文件路径
        """
        # 保存文件 返回文件路径
        file_path,_ = QFileDialog.getSaveFileName(self,"另存为",self.__home_path,"(*.txt)")

        if file_path:
            self.__file_path = file_path
            with open(file_path,"w") as file:
                file.write(plain_text_edit.toPlainText())

            with open(self.__file_path,"r") as file:
                plain_text_edit.setPlainText(file.read())
                file_name = self.get_file_name()
                main_window.set_window_title(False,file_name)
            return file_path

    def print_file(self,plain_text_edit: QPlainTextEdit):
        """打印文件
        """
        printer = QPrinter()
        dialog = QPrintDialog(printer)
        if dialog.exec():
            plain_text_edit.print_(printer)

    def get_file_name(self):
        """获取文件名
        """
        if self.__file_path:
            file_name = self.__file_path.split("/")[-1].split(".")[0]
            return file_name
        else:
            return "无标题"
        
    def star_in_title(self,main_window: QMainWindow) ->  bool:
        """*是否在标题里

        :param main_window: PySide6 QMainWindow
        :return: have or not have ; Ture;False
        """
        window_title =  main_window.get_window_title()
        state = True if "*" in window_title else False
        return state
        
    def new_file_msgbox (self,main_window: QMainWindow,plain_text_edit: QPlainTextEdit):
        """信息框

        :param main_window: PySide6 QMainWindow
        :param plain_text_edit: PySide6 QPlainTextEdit
        """
        star_state = self.star_in_title(main_window)
        if star_state:
            self.message_box(main_window,plain_text_edit)
        else:
            self.new_file(main_window,plain_text_edit)

    def close_megbox(self,main_window: QMainWindow,plain_text_edit: QPlainTextEdit):
        """关闭弹出信息框

        :param main_window: _description_
        :param plain_text_edit: _description_
        """
        star_state = self.star_in_title(main_window)
        if star_state:
            self.message_box(main_window,plain_text_edit)
        else:
            main_window.close()

    def message_box(self,main_window: QMainWindow,plain_text_edit: QPlainTextEdit):
        """信息框

        :param main_window: PySide6 QMainWindow
        :param plain_text_edit: PySide6 QPlainTextEdit
        """
        msg_box =  QMessageBox()
        msg_box.setWindowTitle("记事本")
        msg_box.setText("你想将更改保存到 无标题 吗？")
        msg_box.setStandardButtons(QMessageBox.StandardButton.Save|QMessageBox.StandardButton.Cancel|QMessageBox.StandardButton.Close)
        ret =  msg_box.exec()
        if ret == QMessageBox.StandardButton.Save:
            # 保存
            self.save_file(main_window,plain_text_edit)
        elif ret == QMessageBox.StandardButton.Cancel:
            # 不保存
            self.new_file(main_window,plain_text_edit)
        elif ret == QMessageBox.StandardButton.Close:
            # 取消
            msg_box.close()